import Observer from "@modules/Observer";
import Subject from "@modules/Subject";
import { extend } from "@/business/common";

class ButtonControl {
    controlCheckbox: HTMLInputElement;       // 控制按钮
    addBtn: HTMLElement;                // 添加按钮
    container: HTMLElement;    // 监听者列表

    constructor() {
        this.controlCheckbox = document.getElementById("mainCheckbox") as HTMLInputElement;
        this.addBtn = document.getElementById("addNewObserver")!;
        this.container = document.getElementById("observersContains")!;

        this.init();
    }

    init() {
        const subject = new Subject();

        extend(new Subject(), this.controlCheckbox);

        this.controlCheckbox.addEventListener('click', () => {
            // @ts-ignore
            this.controlCheckbox.notify(this.controlCheckbox.checked)
        });

        this.addBtn.addEventListener('click', this.addNewObserver.bind(this));
    }

    // 添加一个新的复选框
    addNewObserver() {
        // 创建一个复选框
        const check = document.createElement("input");
        check.type = "checkbox";

        // 继承监听者对象
        extend(new Observer(), check);

        // @ts-ignore
        check.update = function(value: boolean) {
            this.checked = value;
        }
        // @ts-ignore
        this.controlCheckbox.addObserver(check);
        this.container.appendChild(check);
    }
}

export default ButtonControl;